﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace ManhXu.Common
{
    public class Logger
    {
        public static string WinDir = Environment.GetEnvironmentVariable("windir");
        public static string TempFolder = System.IO.Path.Combine(WinDir, "Temp");
        public static string LogFile = "MyLib.Log.txt";
        public static string LogFileName = System.IO.Path.Combine(TempFolder, LogFile);
        public static string OutlookAddInFile = "MailboxCentralAddin64.dll";
        public static string InstallRegFile = "install.reg";
        public static string currDir = System.Environment.CurrentDirectory;

        public static bool WriteLog(List<string> text)
        {
            try
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(LogFileName, true))
                {
                    foreach (var s in text)
                    {
                        file.WriteLine(s);
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static void RegisterComInterop(string currDir)
        {
            string outlookAddInFileName = Path.Combine(currDir, OutlookAddInFile);

            string fileRegistry = Path.Combine(currDir, InstallRegFile);

            if (File.Exists(outlookAddInFileName))
            {
                try
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(LogFileName, true))
                    {
                        file.WriteLine(string.Format("{0}: Current Dir: {1}", DateTime.Now, currDir));
                    }

                    //1: Register .NET components with COM

                    string fileRegAsm = Environment.GetEnvironmentVariable("SystemRoot") + "\\Microsoft.NET\\Framework64\\v2.0.50727\\RegAsm.exe";
                    ProcessStartInfo registerComInterop = new ProcessStartInfo(fileRegAsm);

                    registerComInterop.WindowStyle = ProcessWindowStyle.Hidden;
                    registerComInterop.Arguments = string.Format("{0} /codebase", outlookAddInFileName);
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(LogFileName, true))
                    {
                        file.WriteLine(string.Format("{0}: Current Dir: {1}", DateTime.Now, currDir));
                        file.WriteLine(string.Format("{0}: ResAsm.exe: {1}", DateTime.Now, fileRegAsm));
                        file.WriteLine(string.Format("{0}: Addin file: {1}", DateTime.Now, outlookAddInFileName));
                        file.WriteLine(string.Format("{0}: Arguments: {1}.", DateTime.Now, registerComInterop.Arguments));
                    }

                    Process registerComInteropReturnValue = Process.Start(registerComInterop);

                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(LogFileName, true))
                    {
                        file.WriteLine(DateTime.Now + ": Result: " + registerComInteropReturnValue.ExitCode);
                    }


                    //2: Update the .Reg file
                    //UpdateRegFile(fileRegistry);

                    //3: Merge or Import .Reg file Into the Registry

                    string fileReg = Environment.GetEnvironmentVariable("SystemRoot") + "\\system32\\reg.exe";
                    ProcessStartInfo modifyRegistry = new ProcessStartInfo(fileReg);
                    modifyRegistry.WindowStyle = ProcessWindowStyle.Hidden;
                    modifyRegistry.Arguments = string.Format(" import \"{0}\"", fileRegistry);

                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(LogFileName, true))
                    {
                        file.WriteLine(string.Format("{0}: Res.exe: {1}", DateTime.Now, fileRegAsm));
                        file.WriteLine(string.Format("{0}: Reg file: {1}", DateTime.Now, fileRegistry));
                        file.WriteLine(string.Format("{0}: Arguments: {1}.", DateTime.Now, modifyRegistry.Arguments));
                    }

                    Process modifyRegistryReturnValue = Process.Start(modifyRegistry);

                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(LogFileName, true))
                    {
                        file.WriteLine(DateTime.Now + ": Result: " + modifyRegistryReturnValue.ExitCode);
                    }
                }
                catch (Exception ex)
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(LogFileName, true))
                    {
                        file.WriteLine(DateTime.Now + ": Run RegisterComInterop has error. The exception is that: {0}", ex.Message);
                    }
                }
            }
        }

        public static void UpdateRegFile(string filename)
        {
            StringBuilder newFile = new StringBuilder();

            if (!File.Exists(filename))
            {
                return;
            }

            string[] file = File.ReadAllLines(filename);

            foreach (string line in file)
            {
                if (line.Contains(OutlookAddInFile))
                {
                    string fileRenamed = filename.Replace(InstallRegFile, OutlookAddInFile).Replace(@"\", @"/");
                    string newValue = string.Format("\"CodeBase\"=\"file:///{0}\"", fileRenamed);
                    newFile.Append(newValue + "\r\n");
                    continue;
                }
                newFile.Append(line + "\r\n");
            }

            File.WriteAllText(filename, newFile.ToString());
        }
    }
}
